﻿//------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 , Jirisoft , Ltd. 
//------------------------------------------------------------

using System;
using System.Data;
using System.Reflection;

namespace DotNet.Service
{
    using DotNet.Business;
    using DotNet.DbUtilities;
    using DotNet.IService;
    using DotNet.Model;
    using DotNet.Utilities;

    /// <summary>
    /// ILoginService
    /// 
    /// 修改纪录
    /// 
    ///		2009.04.15 版本：1.0 JiRiGaLa 添加接口定义。
    ///		
    /// 版本：1.0
    ///
    /// <author>
    ///		<name>JiRiGaLa</name>
    ///		<date>2009.04.15</date>
    /// </author> 
    /// </summary>
    public class LoginService : System.MarshalByRefObject, ILoginService
    {
        /// <summary>
        /// 用户中心数据库连接
        /// </summary>
        private readonly string UserCenterDbConnection = BaseConfiguration.Instance.UserCenterDbConnection;

        #region public DataTable GetUserDT(BaseUserInfo userInfo) 获得用户列表
        /// <summary>
        /// 获得用户列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>数据表</returns>
        public DataTable GetUserDT(BaseUserInfo userInfo)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            DataTable dataTable = new DataTable(BaseStaffTable.TableName);

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                // 检查用户在线状态(服务器专用)
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                userManager.CheckOnLine();
                // 获取允许登录列表
                string[] names = new string[] { BaseUserTable.FieldEnabled, BaseUserTable.FieldDeleteMark};
                Object[] values = new Object[] { 1, 0};
                dataTable = userManager.GetDT(names, values);
                BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return dataTable;
        }
        #endregion

        #region public DataTable GetUserDT(BaseUserInfo userInfo) 获得内部职员列表
        /// <summary>
        /// 获得内部职员列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>数据表</returns>
        public DataTable GetStaffDT(BaseUserInfo userInfo)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            DataTable dataTable = new DataTable(BaseStaffTable.TableName);

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                // 检查用户在线状态(服务器专用)
                BaseUserManager userManager = new BaseUserManager(dbHelper);
                userManager.CheckOnLine();
                // 获取允许登录列表
                string[] names = new string[]{BaseUserTable.FieldEnabled, BaseUserTable.FieldDeleteMark, BaseUserTable.FieldIsStaff};
                Object[] values = new Object[] { 1, 0, 1 };
                dataTable = userManager.GetDT(names, values);
                BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return dataTable;
        }
        #endregion

        #region public BaseUserInfo LoginByOpenId(BaseUserInfo userInfo, string openId, out string statusCode, out string statusMessage) 按唯一识别码登录
        /// <summary>
        /// 按唯一识别码登录
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="openId">唯一识别码</param>
        /// <param name="statusCode">返回状态码</param>
        /// <param name="statusMessage">返回状消息</param>
        /// <returns>用户实体</returns>
        public BaseUserInfo LoginByOpenId(BaseUserInfo userInfo, string openId, out string statusCode, out string statusMessage)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            BaseUserInfo returnUserInfo = null;
            statusCode = string.Empty;
            statusMessage = string.Empty;
            
            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                // 先侦测是否在线
                userManager.CheckOnLine();
                // 再进行登录
                returnUserInfo = userManager.LoginBySuid(openId, userInfo.IPAddress, userInfo.MACAddress, out statusCode);
                statusMessage = userManager.GetStateMessage(statusCode);
                // 登录时会自动记录进行日志记录，所以不需要进行重复日志记录
                // BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnUserInfo;
        }
        #endregion

        #region public BaseUserInfo LoginByUserName(BaseUserInfo userInfo, string userName, out string statusCode, out string statusMessage) 按用户名登录
        /// <summary>
        /// 按用户名登录
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userName">用户名</param>
        /// <param name="statusCode">返回状态码</param>
        /// <param name="statusMessage">返回状消息</param>
        /// <returns>用户实体</returns>
        public BaseUserInfo LoginByUserName(BaseUserInfo userInfo, string userName, out string statusCode, out string statusMessage)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            BaseUserInfo returnUserInfo = null;
            statusCode = string.Empty;
            statusMessage = string.Empty;
            
            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                // 先侦测是否在线
                userManager.CheckOnLine();
                // 再进行登录
                returnUserInfo = userManager.LoginByUserName(userName, userInfo.IPAddress, userInfo.MACAddress, out statusCode);
                statusMessage = userManager.GetStateMessage(statusCode);
                // 登录时会自动记录进行日志记录，所以不需要进行重复日志记录
                // BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnUserInfo;
        }
        #endregion

        #region public BaseUserInfo UserLogin(BaseUserInfo userInfo, string userName, string password, out string statusCode, out string statusMessage) 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="statusCode">返回状态码</param>
        /// <param name="statusMessage">返回状消息</param>
        /// <returns>用户实体</returns>
        public BaseUserInfo UserLogin(BaseUserInfo userInfo, string userName, string password, out string statusCode, out string statusMessage)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            BaseUserInfo returnUserInfo = null;
            statusCode = string.Empty;
            statusMessage = string.Empty;
            
            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                // 先侦测是否在线
                userManager.CheckOnLine();
                // 再进行登录
                returnUserInfo = userManager.Login(userName, password, userInfo.IPAddress, userInfo.MACAddress, out statusCode);
                if (returnUserInfo != null)
                {
                    PermissionService permissionService = new PermissionService();
                    // 这里是判断用户是否为系统管理员的
                    returnUserInfo.IsAdministrator = permissionService.IsAdministratorByUser(dbHelper, userInfo, returnUserInfo.Id);
                }
                statusMessage = userManager.GetStateMessage(statusCode);
                // 登录时会自动记录进行日志记录，所以不需要进行重复日志记录
                // BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnUserInfo;
        }
        #endregion

        #region public void OnExit(BaseUserInfo userInfo) 用户退出应用程序
        /// <summary>
        /// 用户退出应用程序
        /// </summary>
        /// <param name="userInfo">用户</param>
        public void OnExit(BaseUserInfo userInfo)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                userManager.OnExit(userInfo.Id);
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
        }
        #endregion

        #region public int ServerCheckOnLine() 服务器端检查在线状态
        /// <summary>
        /// 服务器端检查在线状态
        /// </summary>
        /// <returns>离线人数</returns>
        public int ServerCheckOnLine()
        {
            int returnValue = 0;
            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper);
                returnValue = userManager.CheckOnLine();
            }
            catch (Exception ex)
            {
                LogUtil.WriteException(ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }
            return returnValue;
        }
        #endregion

        #region public int CheckOnLine(BaseUserInfo userInfo) 检查在线状态
        /// <summary>
        /// 检查在线状态
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>离线人数</returns>
        public int CheckOnLine(BaseUserInfo userInfo)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            int returnValue = 0;

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper);
                // 设置为在线状态
                userManager.OnLine(userInfo.Id);
                returnValue = userManager.CheckOnLine();
            }
            catch (Exception ex)
            {
                LogUtil.WriteException(ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnValue;
        }
        #endregion

        #region public DataTable GetOnLineState(BaseUserInfo userInfo) 获取在线用户列表
        /// <summary>
        /// 获取在线用户列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>数据表</returns>
        public DataTable GetOnLineState(BaseUserInfo userInfo)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            DataTable dataTable = new DataTable();

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                if (MessageService.LaseCheck == DateTime.MinValue)
                {
                    // 设置为在线状态
                    userManager.OnLine(userInfo.Id);
                    // 检查用户在线状态(服务器专用)
                    userManager.CheckOnLine();
                    MessageService.LaseCheck = DateTime.Now;
                }
                else
                {
                    // 2008.01.23 JiRiGaLa 修正错误
                    TimeSpan timeSpan = DateTime.Now - MessageService.LaseCheck;
                    if ((timeSpan.Minutes * 60 + timeSpan.Seconds) >= BaseSystemInfo.OnLineCheck)
                    {
                        // 设置为在线状态
                        userManager.OnLine(userInfo.Id);
                        // 检查用户在线状态(服务器专用)
                        userManager.CheckOnLine();
                        MessageService.LaseCheck = DateTime.Now;
                    }
                }
                // 获取在线状态列表
                dataTable = userManager.GetOnLineStateDT();
                // BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return dataTable;
        }
        #endregion

        #region public int SetPassword(BaseUserInfo userInfo, string[] userIds, string password, out string statusCode, out string statusMessage) 设置密码
        /// <summary>
        /// 设置密码
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">被设置的职员主键</param>
        /// <param name="password">新密码</param>
        /// <param name="statusCode">返回状态码</param>
        /// <param name="statusMessage">返回状消息</param>
        /// <returns>影响行数</returns>
        public int SetPassword(BaseUserInfo userInfo, string[] userIds, string password, out string statusCode, out string statusMessage)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            statusCode = string.Empty;
            statusMessage = string.Empty;
            int returnValue = 0;

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                returnValue = userManager.BatchSetPassword(userIds, password, out statusCode);
                // 获得状态消息
                statusMessage = userManager.GetStateMessage(statusCode);
            }
            catch (Exception ex)
            {
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnValue;
        }
        #endregion
        
        #region public int ChangePassword(BaseUserInfo userInfo, string oldPassword, string newPassword, out string statusCode, out string statusMessage) 修改密码
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="oldPassword">原始密码</param>
        /// <param name="newPassword">新密码</param>
        /// <param name="statusCode">返回状态码</param>
        /// <param name="statusMessage">返回状消息</param>
        /// <returns>影响行数</returns>
        public int ChangePassword(BaseUserInfo userInfo, string oldPassword, string newPassword, out string statusCode, out string statusMessage)
        {
            // 写入调试信息
            #if (DEBUG)
                int milliStart = BaseBusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif
            statusCode = string.Empty;
            statusMessage = string.Empty;
            int returnValue = 0;

            IDbHelper dbHelper = DbHelperFactory.GetHelper();
            try
            {
                dbHelper.Open(UserCenterDbConnection);
                // 事务开始
                // dbHelper.BeginTransaction();
                BaseLogManager.Instance.Add(dbHelper, userInfo, MethodBase.GetCurrentMethod());
                BaseUserManager userManager = new BaseUserManager(dbHelper, userInfo);
                returnValue = userManager.ChangePassword(oldPassword, newPassword, out statusCode);
                // 获得状态消息
                statusMessage = userManager.GetStateMessage(statusCode);
                // 事务递交
                // dbHelper.CommitTransaction();
            }
            catch (Exception ex)
            {
                // 事务回滚
                // dbHelper.RollbackTransaction();
                BaseExceptionManager.LogException(dbHelper, userInfo, ex);
                throw ex;
            }
            finally
            {
                dbHelper.Close();
            }

            // 写入调试信息
            #if (DEBUG)
                BaseBusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif
            return returnValue;
        }
        #endregion
    }
}
